package com.expert.miniapp.controller;

import com.expert.miniapp.dao.UserResourceLibrary;
import com.expert.miniapp.dto.ResourceStatisticsDTO;
import com.expert.miniapp.dto.ResultDTO;
import com.expert.miniapp.dto.UserResourceLibraryDTO;
import com.expert.miniapp.service.UserResourceLibraryService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * UserResourceLibraryController - 用户资源库控制器
 * 提供用户资源库管理相关接口
 *
 * @author System
 * @since 2025-10-28
 */
@RestController
@RequestMapping("/api/user-resource-library")
@CrossOrigin(origins = "*")
public class UserResourceLibraryController {

    private static final Logger logger = LoggerFactory.getLogger(UserResourceLibraryController.class);

    @Autowired
    private UserResourceLibraryService userResourceLibraryService;

    /**
     * 添加资源到资源库
     *
     * @param requestBody 请求体，包含 userId, resourceType, resourceId, notes
     * @return 新创建的资源库记录
     */
    @PostMapping(produces = "application/json;charset=UTF-8")
    public ResultDTO<UserResourceLibrary> addResource(@RequestBody Map<String, String> requestBody) {
        String userId = requestBody.get("userId");
        String resourceType = requestBody.get("resourceType");
        String resourceId = requestBody.get("resourceId");
        String notes = requestBody.get("notes");

        logger.info("接收到添加资源请求: userId={}, resourceType={}, resourceId={}",
                    userId, resourceType, resourceId);

        try {
            UserResourceLibrary library = userResourceLibraryService.addResource(
                    userId, resourceType, resourceId, notes
            );
            logger.info("资源添加成功: libraryId={}", library.getLibraryId());
            return ResultDTO.success(library);
        } catch (IllegalArgumentException e) {
            logger.warn("添加资源失败: {}", e.getMessage());
            return ResultDTO.error(e.getMessage());
        } catch (Exception e) {
            logger.error("添加资源失败", e);
            return ResultDTO.error("添加资源失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的资源库列表（支持分页、类型筛选、关键词搜索）
     *
     * @param userId 用户ID（必填）
     * @param resourceType 资源类型（可选，"all"或不传表示全部）
     * @param keyword 搜索关键词（可选）
     * @param pageNum 页码（可选，默认1）
     * @param pageSize 每页数量（可选，默认10）
     * @return 资源库列表分页信息
     */
    @GetMapping(produces = "application/json;charset=UTF-8")
    public ResultDTO<PageInfo<UserResourceLibraryDTO>> getResourceList(
            @RequestParam String userId,
            @RequestParam(required = false) String resourceType,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize) {

        logger.info("接收到查询资源库列表请求: userId={}, resourceType={}, keyword={}, pageNum={}, pageSize={}",
                    userId, resourceType, keyword, pageNum, pageSize);

        try {
            PageInfo<UserResourceLibraryDTO> pageInfo = userResourceLibraryService.getResourceList(
                    userId, resourceType, keyword, pageNum, pageSize
            );
            logger.info("查询到 {} 条资源", pageInfo.getTotal());
            return ResultDTO.success(pageInfo);
        } catch (IllegalArgumentException e) {
            logger.warn("查询资源库列表失败: {}", e.getMessage());
            return ResultDTO.error(e.getMessage());
        } catch (Exception e) {
            logger.error("查询资源库列表失败", e);
            return ResultDTO.error("查询资源库列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户资源库统计信息
     *
     * @param userId 用户ID
     * @return 统计信息（各类资源数量）
     */
    @GetMapping(value = "/statistics", produces = "application/json;charset=UTF-8")
    public ResultDTO<ResourceStatisticsDTO> getStatistics(@RequestParam String userId) {
        logger.info("接收到查询统计信息请求: userId={}", userId);

        try {
            ResourceStatisticsDTO statistics = userResourceLibraryService.getStatistics(userId);
            logger.info("统计信息查询成功: total={}", statistics.getTotal());
            return ResultDTO.success(statistics);
        } catch (IllegalArgumentException e) {
            logger.warn("查询统计信息失败: {}", e.getMessage());
            return ResultDTO.error(e.getMessage());
        } catch (Exception e) {
            logger.error("查询统计信息失败", e);
            return ResultDTO.error("查询统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 检查资源是否已在用户资源库中
     *
     * @param userId 用户ID
     * @param resourceType 资源类型
     * @param resourceId 资源ID
     * @return 检查结果（是否存在、libraryId）
     */
    @GetMapping(value = "/check", produces = "application/json;charset=UTF-8")
    public ResultDTO<Map<String, Object>> checkResourceExists(
            @RequestParam String userId,
            @RequestParam String resourceType,
            @RequestParam String resourceId) {

        logger.info("接收到检查资源存在请求: userId={}, resourceType={}, resourceId={}",
                    userId, resourceType, resourceId);

        try {
            Map<String, Object> result = userResourceLibraryService.checkResourceExists(
                    userId, resourceType, resourceId
            );
            logger.info("资源存在检查完成: exists={}", result.get("exists"));
            return ResultDTO.success(result);
        } catch (IllegalArgumentException e) {
            logger.warn("检查资源存在失败: {}", e.getMessage());
            return ResultDTO.error(e.getMessage());
        } catch (Exception e) {
            logger.error("检查资源存在失败", e);
            return ResultDTO.error("检查资源存在失败: " + e.getMessage());
        }
    }

    /**
     * 获取资源库单个资源的完整详情
     *
     * @param libraryId 资源库ID
     * @return 资源库DTO(包含资源详情)
     */
    @GetMapping(value = "/{libraryId}", produces = "application/json;charset=UTF-8")
    public ResultDTO<UserResourceLibraryDTO> getResourceDetail(@PathVariable String libraryId) {
        logger.info("接收到查询资源详情请求: libraryId={}", libraryId);

        try {
            UserResourceLibraryDTO detail = userResourceLibraryService.getResourceDetail(libraryId);
            logger.info("资源详情查询成功: resourceType={}", detail.getResourceType());
            return ResultDTO.success(detail);
        } catch (IllegalArgumentException e) {
            logger.warn("查询资源详情失败: {}", e.getMessage());
            return ResultDTO.error(e.getMessage());
        } catch (RuntimeException e) {
            logger.warn("查询资源详情失败: {}", e.getMessage());
            return ResultDTO.error(e.getMessage());
        } catch (Exception e) {
            logger.error("查询资源详情失败", e);
            return ResultDTO.error("查询资源详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新资源库备注
     *
     * @param libraryId 资源库ID
     * @param requestBody 请求体，包含 notes
     * @return 是否成功
     */
    @PutMapping(value = "/{libraryId}", produces = "application/json;charset=UTF-8")
    public ResultDTO<Void> updateNotes(
            @PathVariable String libraryId,
            @RequestBody Map<String, String> requestBody) {

        String notes = requestBody.get("notes");

        logger.info("接收到更新备注请求: libraryId={}, notes={}", libraryId, notes);

        try {
            boolean success = userResourceLibraryService.updateNotes(libraryId, notes);
            if (success) {
                logger.info("备注更新成功");
                return ResultDTO.success(null);
            } else {
                return ResultDTO.error("资源库记录不存在");
            }
        } catch (IllegalArgumentException e) {
            logger.warn("更新备注失败: {}", e.getMessage());
            return ResultDTO.error(e.getMessage());
        } catch (Exception e) {
            logger.error("更新备注失败", e);
            return ResultDTO.error("更新备注失败: " + e.getMessage());
        }
    }

    /**
     * 从资源库删除资源
     *
     * @param libraryId 资源库ID
     * @return 是否成功
     */
    @DeleteMapping(value = "/{libraryId}", produces = "application/json;charset=UTF-8")
    public ResultDTO<Void> deleteResource(@PathVariable String libraryId) {
        logger.info("接收到删除资源请求: libraryId={}", libraryId);

        try {
            boolean success = userResourceLibraryService.deleteResource(libraryId);
            if (success) {
                logger.info("资源删除成功");
                return ResultDTO.success(null);
            } else {
                return ResultDTO.error("资源库记录不存在");
            }
        } catch (IllegalArgumentException e) {
            logger.warn("删除资源失败: {}", e.getMessage());
            return ResultDTO.error(e.getMessage());
        } catch (Exception e) {
            logger.error("删除资源失败", e);
            return ResultDTO.error("删除资源失败: " + e.getMessage());
        }
    }
}
